import { FC, MouseEvent } from 'react';
import styles from './index.module.scss';
import { Spin } from 'antd';
import useGetComponentInfo from '../../../../../hooks/useGetComponentInfo';
import { ComponentInfoType, moveComponent } from '../../../../../store/componentReducer';
import { getComponentConfigByType } from '../../../../../components/QuestionComponents';
import { useDispatch } from 'react-redux';
import { changeSelectedId } from '../../../../../store/componentReducer';
import useBindCanvasKeyPress from '../../../../../hooks/useBindCanvasKeyPress';
import SortableContainer from '../../../../../components/DragSortable/SortableContainer';
import SortableItem from '../../../../../components/DragSortable/SortableItem';
import classNames from 'classnames';
type PropsType = {
  loading: boolean;
};
const EditCanvas: FC<PropsType> = (props: PropsType) => {
  const { loading } = props;
  const { componentList, selectedId } = useGetComponentInfo();
  const dispatch = useDispatch();
  useBindCanvasKeyPress();

  function genComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo;
    const componentConfig = getComponentConfigByType(type);
    console.log('componentConfig', componentConfig);
    if (!componentConfig) return;
    const { Component } = componentConfig;
    return <Component {...props} />;
  }

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '60px' }}>
        <Spin />
      </div>
    );
  }

  function handleClick(event: MouseEvent<HTMLDivElement>, id: string) {
    event.stopPropagation();
    dispatch(changeSelectedId(id));
  }
  function handleDragEnd(oldIndex: number, newIndex: number) {
    console.log(oldIndex, newIndex);
    dispatch(moveComponent({ oldIndex, newIndex }));
  }

  return (
    <SortableContainer
      items={componentList.map((c) => ({ ...c, id: c.fe_id }))}
      onDragEnd={handleDragEnd}
    >
      <div className={styles.canvas}>
        {componentList
          .filter((c) => !c.isHidden)
          .map((c) => {
            const { fe_id, isLocked } = c;
            const wrapperDefaultClassName = styles['component-wrapper'];
            const selectedClassName = styles.selected;
            const lockedClassName = styles.locked;
            const wrapperClassName = classNames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: fe_id === selectedId,
              [lockedClassName]: isLocked,
            });
            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div className={wrapperClassName} onClick={(event) => handleClick(event, fe_id)}>
                  <div className={styles.component}>{genComponent(c)}</div>
                </div>
              </SortableItem>
            );
          })}
      </div>
    </SortableContainer>
  );
};

export default EditCanvas;
